//
//  AdManager.m
//  takeout
//
//  Created by Mac on 12-9-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AdManager.h"
#import "ResolveXML.h"
#import "Constants.h"
#import "Ad.h"

@implementation AdManager


-(NSArray *) getSupplierByUrl:(NSString *)URIString{
    NSURL *url = [[NSURL alloc] initWithString:[URIString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest* request = [NSMutableURLRequest new];    
    [request setURL:url];    
    [request setHTTPMethod:@"GET"]; 
    NSHTTPURLResponse* response;    
    
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 
    NSString* responseXMLResult=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithXMLString: responseXMLResult options:0 error:&error];
    

    
    
    NSArray *children = [doc.rootElement children]; 
    NSMutableArray *result = nil;
    for (GDataXMLElement *element in children) {
        if ([element isKindOfClass:[GDataXMLElement class]]) 
        {
            Ad *ad=[[Ad alloc]init];
            ad.adId=[[[element childAtIndex:0] stringValue] intValue];
            ad.type=[[element childAtIndex:1] stringValue];
            ad.value=[[element childAtIndex:2] stringValue];
            ad.imgUrl=[[element childAtIndex:3] stringValue];
            ad.position=[[element childAtIndex:4] stringValue];
            ad.sort=[[[element childAtIndex:5] stringValue] intValue];
            ad.desc=[[element childAtIndex:6] stringValue];
            ad.createTime=[[element childAtIndex:7] stringValue];
            ad.updateTime=[[element childAtIndex:8] stringValue];
            if (result == nil) {
                result = [NSMutableArray arrayWithObject:ad];
            }else{
                [result addObject:ad];
            }

        }
    } 
    return result;
}

//根据投放位置显示广告
-(NSArray *)getSupplierByPosition:(NSString *)Position{
    NSString *URIString = [NSString stringWithFormat:SERVICE_DOMAIN, [NSString stringWithFormat: SERVICE_AD_BY_POSITION,[NSString stringWithFormat:@"?position=%@",Position]]];
    return [self getSupplierByUrl:URIString];
}



@end
